package com.ygqh.baby.service.ngmm.http;

import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.http.HttpClient;
import com.foxinmy.weixin4j.http.HttpClientException;
import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpRequest;
import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.entity.FormUrlEntity;
import com.foxinmy.weixin4j.http.entity.HttpEntity;
import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.ygqh.baby.service.ngmm.exception.NgmmException;

public class NgmmRequestExecutor {
	protected final Logger logger = Logger.getLogger(this.getClass());
	
	private final HttpClient httpClient;
	
	public NgmmRequestExecutor() {
		this.httpClient = HttpClientFactory.getInstance();
	}

	/**
	 * POST请求
	 * @param baseUrl	请求地址
	 * @param body		参数内容
	 * @return
	 * @throws NgmmException
	 */
	public NgmmResponse post(String baseUrl, Map<String, String> body) throws NgmmException {
		String url = baseUrl + "?method=" + body.get("method");
		HttpEntity entity = new FormUrlEntity(body);
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setEntity(entity);
		return doRequest(request);
	}

	private NgmmResponse doRequest(HttpRequest request) throws NgmmException {
		try {
			HttpResponse httpResponse = httpClient.execute(request);
			NgmmResponse response = new NgmmResponse(httpResponse);
			handleResponse(response);
			return response;
		} catch (HttpClientException e) {
			throw new NgmmException(e);
		}
	}

	private void handleResponse(NgmmResponse response) throws NgmmException {
		JSONObject result = response.getAsJson();
		if (0 >= result.getLong("status")) {
			throw new NgmmException(result.getLong("status") + "", result.getString("msg"));
		}
	}

}
